<?php

/** 
* article.php
*
* Create on 2015-1-19
* Create by TT
*/
namespace haibao\www\data;
use haibao\frame\data\query\Condition;

use \haibao\cms\model\filter\Article as ArticleFilter;

class Article extends \haibao\www\data\BaseMysql {
	private static $hcorrection = 'HC_ERROR_REPLACE';
	public function __construct() {
		parent::__construct ( '\haibao\cms\model\data\Article' );
	}
	
	/**
	 * 添加文章
	 *
	 * @param \haibao\cms\model\data\Article $articleModel        	
	 */
	public function addArticle($articleModel) {
		self::beginTranscation ();
		try {
			
			$this->add ( $articleModel );
			$this->addArticleRelationTable ( $articleModel );
			//新库app推送
			if($articleModel->AppColum){
				$this->addArticleToApp($articleModel);
			}
			
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)) {
			// 老记录
			$this->addOldArticleData($articleModel);
		}		
	}
	
	/**
	 * 修改文章信息
	 *
	 * @param \haibao\cms\model\data\Article $articleModel        	
	 * @throws Exception
	 */
	public function updateArticle($articleModel) {
		self::beginTranscation ();
		try {
			$this->updateById($articleModel->Id, array(
					ArticleFilter::CONDITION_FIELD_NAME_TITLE=>$articleModel->Title,
					ArticleFilter::CONDITION_FIELD_NAME_SHORTTITLE=>$articleModel->ShortTitle,
					ArticleFilter::CONDITION_FIELD_NAME_SOURCE=>$articleModel->Source,
					ArticleFilter::CONDITION_FIELD_NAME_ISPSEUDONYM=>$articleModel->IsPseudonym,
					ArticleFilter::CONDITION_FIELD_NAME_SUMMARY=>$articleModel->Summary,
					ArticleFilter::CONDITION_FIELD_NAME_ARTICLE_CONTENT=>$articleModel->Content,
					ArticleFilter::CONDITION_FIELD_NAME_PUBLISHTIME=>$articleModel->PublishTime,
					ArticleFilter::CONDITION_FIELD_NAME_LEVEL=>$articleModel->Level,
					ArticleFilter::CONDITION_FIELD_NAME_PUBLISHED=>$articleModel->Published,
					ArticleFilter::CONDITION_FIELD_NAME_ARTICLE_SOURCE=>$articleModel->ArticleSource,			
					));
			
			$this->addArticleRelationTable ( $articleModel, false );
			
			//新库app推送
			if($articleModel->AppColum){
				$this->addArticleToApp($articleModel);
			}
		
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		if ( \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD) ) {
			// 老记录
			$articleModelCopy = clone $articleModel;
			$this->updateOldArticleData ($articleModelCopy);
		}
	}
	
	/**
	 * 修改文章状态
	 *
	 * @param int $articleId        	
	 * @param int $status        	
	 */
	public function updateArticleStatus($articleId, $status = \haibao\cms\model\data\Article::STATUS_ENABLE) {
		$sql = 'update Article set Status=%s where Id=%s';
		$arrValues = array (
				$status,
				$articleId 
		);	
		$this->query ( $sql, $arrValues );
		if ( \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD) ) {
			// 老记录
			$this->updateOldArticleStatus ( $articleId, $status );
		}
	}
	
	/**
	 * 修改文章发布状态
	 * @param Array/int $articleId        	
	 * @param int $published  0:未发布，1：已经发布，2：预发布
	 */
	
	public function updateArticlePublish($articleId, $published = \haibao\cms\model\data\Article::PUBLISHED_YES) {
		$sql = "";
		if (is_int ( $articleId )) {
			$sql = "update Article set Published=%s where  Id=%s  ";
			$arrValues = array (
					$published,
					$articleId					
			);			
			$this->query ( $sql, $arrValues );
		} elseif (is_array ( $articleId )) {
			$Ids = join(',',$articleId);
			$sql = "update Article set Published=".$published." where Id in (".$Ids.")  ";
			$this->query ( $sql );
		}
		if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD) && $sql) {
			// 老记录
			$this->updateOldArticlePublish ( $articleId, $published );
		}
	}
	
	/**
	 * 通过文章ids 获得点击数
	 */
	public function getClickNumsByArticleIds($articleIds){
		if(!$articleIds){
			return false;
		}
		$articleIds = (array)$articleIds;
		$articleIdStr = implode(',', $articleIds);
		$str = preg_replace('/(\d+)/', '%s', $articleIdStr);
		$sql = "select ArticleId,ClickNum from ArticleProperty where ArticleId IN (".$str.")";
		$result = $this->query($sql, $articleIds);
		$data = array();
		while ($result->fetch_assoc()){
			if(!isset($data[$result->getData('ArticleId')])){
				$data[$result->getData('ArticleId')] = $result->getData('ClickNum');
			}
		}
		return $data;
	}
	/**
	 * 获取文章绑定图集Id
	 */
	public function getImageCollIdsByArticleIds($articleIds){
		$articleIds = (array)$articleIds;
		$articleIdStr = implode(',', $articleIds);
		$str = preg_replace('/(\d+)/', '%s', $articleIdStr);
		
		$sql = "select ArticleId,ImageCollectiveId from ImageCollectiveArticle where ArticleId IN (".$str.")";
		$result  = $this->query($sql,$articleIds);
		$data = array();
		while($result->fetch_assoc()){
			if(!isset($data[$result->getData('ArticleId')])){
				$data[$result->getData('ArticleId')] = $result->getData('ImageCollectiveId');
			}
		}
		return $data;
	}
	/**
	 * 修改文章等级
	 *
	 * @param int $articleId        	
	 * @param int $level        	
	 */
	public function updateArticleLevel($articleId, $level) {
		$sql = 'update Article set Level=%s where Id=%s';
		$arrValues = array (
				$level,
				$articleId 
		);
		$this->query ( $sql, $arrValues );
		if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)) {
			// 老记录
			$this->updateOldArticleLevel ( $articleId, $level );
		}
	}
	
	/**
	 * 修改文章审核状态
	 *
	 * @param int $articleId        	
	 * @param int $auditType        	
	 */
	public function updateArticleAuditType($articleId, $auditType = \haibao\cms\model\data\Article::AUDITTYPE_YES) {
		$sql = 'update Article set AuditType=%s where Id=%s';
		$arrValues = array (
				$auditType,
				$articleId 
		);
		$this->query ( $sql, $arrValues );
		if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)) {
			// 老记录
			$this->updateOldArticleAuditType ();
		}
	}
	
	/**
	 * 修改文章影响数
	 *
	 * @param int $articleId        	
	 * @param int $num        	
	 */
	public function updateEditClickNumByArticleId($articleId, $num) {
		$sql = 'update ArticleProperty set EditClickNum=%s where ArticleId=%s';
		$arrValues = array (
				$num,
				$articleId 
		);
		$this->query ( $sql, $arrValues );
		if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)) {
			// 老记录
			$this->updateOldArticleAuditType();
		}
	}
	
	/**
	 * 修改内容仓库
	 *
	 * @param int $id        	
	 * @param string $content        	
	 */
	public function updateContentDepot($id, $content) {
		$sql = 'update ContentDepot set Content=%s where Id=%s';
		$arrValues = array (
				$content,
				$id 
		);
		$this->query ($sql, $arrValues );
	}
	
	/**
	 * 错误内容替换
	 */
	public function errorContentReplace() {
		$contentReplaceArr = $this->getCache ( self::$hcorrection );
		if (empty($contentReplaceArr)) {
			$this->setConfig ( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$sql = "select wrong,correct from hcorrection where active = 1 ";
			$result = $this->query ( $sql );
			$contentReplaceArr = array();
			while ($result->fetch_assoc()){
				$contentReplaceArr['wrong'][] = $result->getData('wrong');
				$contentReplaceArr['correct'][] = $result->getData('correct');
			}
			if ($contentReplaceArr) {
				$this->setCache ( self::$hcorrection, $contentReplaceArr );
			} else {
				$this->setCache ( self::$hcorrection, 1 );
			}
		} else {
			if(!is_array($contentReplaceArr)){
				$contentReplaceArr = array();
			}
		}
		return $contentReplaceArr;
	}
	
	public function getArticleOldIdById($articleId){
		$sql="select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s ";
		$result = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		return $result;
	}
	
	public function getArticleStatisticList($queryArr,$isEditorSta = true){
		$sql = "select a.CreateBy,a.Author,COUNT(DISTINCT a.Id) as ArticleCount,SUM(b.ClickNum) as ClickNum,SUM(b.VoteNum) as VoteNum,SUM(b.CommentNum) as CommentNum from Article as a";
		if(!$isEditorSta){
			$sql = "select Count(a.Id) as ArticleNum, SUM(b.ClickNum) as ClickNum,SUM(b.VoteNum) as VoteNum,SUM(b.CommentNum) as CommentNum from Article as a";
		}
		$sql .= " LEFT JOIN ArticleProperty as b on a.Id = b.ArticleId";
		if(!empty($queryArr['tagIds'])){
			$sql .= " LEFT JOIN ArticleTag as c on a.Id = c.ArticleId";
		}
		$sql .= " where a.CreateBy<>477";
		if(!empty($queryArr['createBy'])){
			if(is_array($queryArr['createBy'])){
				$sql .= " And a.CreateBy in (".implode(',', $queryArr['createBy']).")";
			} else {
				$sql .= " And a.CreateBy = ".$queryArr['createBy'];
			}
		}
		if(!empty($queryArr['tagIds'])){
			$sql .= " And c.TagId in (".$queryArr['tagIds'].")";
		}
		if(isset($queryArr['level'])){
			$level = (int)$queryArr['level'];
			if($level <= 7){
				$sql .= " And a.Level = ".$level;
			} else {
				$sql .= " And a.Level >= ".$level - 7;
			}
		}
		if(!empty($queryArr['title'])){
			$sql .= " And a.Title like '%".$this->escape($queryArr['title'])."%'";
		}
		if(!empty($queryArr['publishTimeType'])){
			$publishTimeType = (int)$queryArr['publishTimeType'];
			switch ($publishTimeType){
				case 1:
					$sql .= " And a.PublishTime >= '".date('Y-m-d', strtotime('-1 day'))."' And a.PublishTime <= '".date('Y-m-d',time())."'";
					break;
				case 2:
					$sql .= " And a.PublishTime >= '".date('Y-m-d', strtotime('-7 day'))."' And a.PublishTime <= '".date('Y-m-d',time())."'";
					break;
				case 3:
					$sql .= " And a.PublishTime >= '".date('Y-m-d', strtotime('-30 day'))."' And a.PublishTime <= '".date('Y-m-d',time())."'";
					break;
			}
		}
		
		if(!empty($queryArr['startDate'])){
			$sql .= " And a.PublishTime >= '".$queryArr['startDate']."'";
		}
		
		if(!empty($queryArr['endDate'])){
			$sql .= " And a.PublishTime <= '".$queryArr['endDate']."'";
		}
		
		$articleList = array();
		$listCount = 0;
		$articleNum = 0;
		$clickNum = 0;
		$commentNum = 0;
		$voteNum = 0;
		if($isEditorSta){
			$sql .= " GROUP BY a.CreateBy";
		}
		$result = $this->query($sql);
		
		$listCount = 0;
		if(!$isEditorSta){
			while($result->fetch_assoc()){
				$clickNum = $result->getData('ClickNum');
				$commentNum = $result->getData('CommentNum');
				$voteNum = $result->getData('VoteNum');
				$articleNum = $result->getData('ArticleNum');
			}
		}else{
			$listCount = $result->getMysqlResult()->num_rows;
			while($result->fetch_assoc()){
				$articleNum = $articleNum + $result->getData('ArticleCount');
				$clickNum = $clickNum + $result->getData('ClickNum');
				$commentNum = $commentNum + $result->getData('CommentNum');
				$voteNum = $voteNum + $result->getData('VoteNum');
			}
			$orderStr = " order by ArticleCount desc";
			if(!empty($queryArr['orderType'])){
				$orderType = (int)$queryArr['orderType'];
				$orderVal = $queryArr['orderVal'];
				if(empty($orderVal)){
					$orderVal = "";
				} else {
					$orderVal = "desc";
				}
				switch ($orderType){
					case 1:
						$orderStr = " order by ClickNum ".$orderVal;
						break;
					case 2:
						$orderStr = " order by VoteNum ".$orderVal;
						break;
					case 3:
						$orderStr = " order by CommentNum ".$orderVal;
						break;
					case 4:
						$orderStr = " order by ArticleCount ".$orderVal;
						break;
					default:
						$orderStr = " order by a.PublishTime ".$orderVal;
						break;
				}
			}
			$sql .= $orderStr;
			$limit ="";
			if(!isset($queryArr['source'])){
				$limit = " Limit 0,20";
				if(!empty($queryArr['page']) && $queryArr['page'] > 1){
					$startCount = ($queryArr['page'] - 1) * 20 + 1;
					$limit = " Limit ".$startCount.",20";
				}
			}
			$sql .= $limit;
			$result = $this->query($sql);
			$k = 0;
			while($result->fetch_assoc()){
				$articleList[$k]['Author']=$result->getData('Author');
				$articleList[$k]['UserId']=$result->getData('CreateBy');
				$articleList[$k]['ArticleCount']=$result->getData('ArticleCount');
				$articleList[$k]['ClickNum']=$result->getData('ClickNum');
				$articleList[$k]['CommentNum']=$result->getData('CommentNum');
				$articleList[$k]['VoteNum']=$result->getData('VoteNum');
				$k++;
			}
		}
		
		return array('List'=>$articleList,'Count'=>$listCount,'ArticleNum'=>$articleNum,'ClickNum'=>$clickNum,'CommentNum'=>$commentNum,'VoteNum'=>$voteNum);
	}
	
	/**
	 * 公用用新文章id获得新图片id
	 * @param $articleIds array or int or string
	 */
	public function publicImageIdByArticleId($articleId){
		
		$sql="select ImageId from ArticleImage where ArticleId = %s order by PicOrder asc";
		$result = $this->query($sql,array($articleId))->fetch_assoc();
		return $result;
	}
	
	public function getProImageByArticleId($articleId){
		$sql="select ImageId,PicType,Level from ArticleProImage where ArticleId = %s ";
		$result = $this->query($sql,array($articleId));
		$proImags=array();
		$key=0;
		while($result->fetch_assoc()){			
			$proImags[$key]['ImageId']=$result->getData('ImageId');
			$proImags[$key]['PicType']=$result->getData('PicType');
			$proImags[$key]['Level']=$result->getData('Level');	
			$key++;
		}		
		return $proImags;
	}
	
	/**
	 * 得文章导读图
	 * @param array $articleIds
	 * @param int $level
	 * @return array(ArticleId=>ImageId)
	 */
	public function getProImageFigure($articleIds,$level){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql = "select ArticleId,ImageId,PicUrl from `ArticleProImage` where `ArticleId` in (".$str.") and level = %s and `PicType` =1";
		$articleIds[] = $level;
		$result = $this->query($sql, $articleIds);
		
		$proImags = array();
		if($result->fetch_assoc()){
			while($result->fetch_assoc()){
				$proImags[$result->getData('ArticleId')] = $result->getData('PicUrl');
			}
		}
		return $proImags;
	}
	/**
	 * 获取第一张图
	 */
	public function getFirstPic($articleIds){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql = "select `ArticleId`,`ImageId`,`PicUrl` from `ArticleImage` where `ArticleId` in (".$str.") and `PicOrder` = 1";
		$result = $this->query($sql, $articleIds);
		$firstImgIds= array();
		while($result->fetch_assoc()){
			if(!isset($firstImgIds[$result->getData('ArticleId')])){
				$firstImgIds[$result->getData('ArticleId')] = $result->getData('PicUrl');
			}
		}
		return $firstImgIds;
	}
	
	/**
	 * 设置文章图片类型（导读图/封面图）
	 * @param : int $articleId 文章ID
	 * @param : object $imageInfo 图片信息
	 * @param : int $imgType 图片类型
	 * @param : int $level 等级
	 */
	public function setImageType($articleId,$imageInfo,$imgType,$level){
		
		$sql = 'delete from `ArticleProImage` where ArticleId=%s and PicType=%s and Level=%s';
		$this->query($sql,array($articleId,$imgType,$level));
		$sql = 'insert into `ArticleProImage` (ArticleId,ImageId,PicType,Level,Width,Height,PicUrl) values (%s,%s,%s,%s,%s,%s,%s)';
		$valArr = array();
		array_push($valArr,$articleId);
		array_push($valArr,$imageInfo->Id);
		array_push($valArr,$imgType);
		array_push($valArr,$level);
		array_push($valArr,$imageInfo->Width);
		array_push($valArr,$imageInfo->Height);
		array_push($valArr,$imageInfo->Filename);
		$this->query($sql,$valArr);
		$insertId = $this->getDb()->insert_id;
		if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)) {
			// 老记录
			$this->setOldImageType($articleId,$imageInfo,$imgType,$level);
		}
		return $insertId;
		
	}
	/**
	 * 删除文章自定义导读图
	 * @param : int $imageProId
	 */
	public function delProImageByProId($imageProId){
		$sql = 'select ArticleId,Level from `ArticleProImage` where Id=%s';
		$result = $this->query($sql,array($imageProId))->fetch_assoc();
			if($result){
				$sql = 'delete from `ArticleProImage` where Id=%s';
				$this->query($sql,array($imageProId));
			
			if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)) {
				// 老记录
				$this->delOldProImageByProId($result['ArticleId'],$result['Level']);
			}
		}
	}
	
	/**
	 * 删除文章标签
	 * @param int $articleId
	 * @param int $tagId
	 * @throws BusinessException
	 */
	public function delArticleTag($articleId,$tagId){
		$sql = 'delete from `ArticleTag` where ArticleId=%s and TagId=%s';
		$this->query($sql,array($articleId,$tagId));
		if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)) {
			// 老记录
			$this->delOldArticleTag($articleId,$tagId);
		}
	}
	
	public function batchUpdateAircleTag($articleModel){
		$this->initNewDB();
		$this->addArticleTag($articleModel->ArticleTag, $articleModel->Id);
		if (\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)) {
			$article = $this->getOneById($articleModel->Id);
			$article->ArticleTag = $articleModel->ArticleTag;
			// 老记录
			$sql = 'select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey =%s';
			$result = $this->query($sql,array('Article',$articleModel->Id))->fetch_assoc();
			$documentId = $result['OldPrimaryKey'];
			//没有找到新-老关系对应记录
			if(empty($documentId)) return NULL;
			$this->saveOldArticleTag ( $article, $documentId ,false);
		}
	}
	/**
	 * 检查文章是否有此标签
	 */
	public function checkArticleTags($articleIds,$tagIds){
		$tagStr = preg_replace('/(\d+)/', '%s', implode(',', $tagIds));
		$idStr = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql = "select `ArticleId`,`TagId` from `ArticleTag` where `TagId` in (".$tagStr.") and `ArticleId` in (".$idStr.")";
		$result = $this->query($sql, array_merge($tagIds, $articleIds));
		$articleTag= array();
		while($result->fetch_assoc()){
			if(!isset($articleTag[$result->getData('ArticleId')][$result->getData('TagId')])){
				$articleTag[$result->getData('ArticleId')][] = $result->getData('TagId');
			}
		}
		return $articleTag;
	}
	
	
	/**
	 * 预发布文章id
	 */
	public function getCronArticleId(){		
		$articleId=array();
		$today = date('Y-m-d H:i:s',time());
		$sql="select Id from Article where Published = 2 and Status = 0 and PublishTime<='".$today."' ";
		$result = $this->query($sql,array());
		while($result->fetch_assoc()){
			$articleId[] = $result->getData('Id');
		}
		return $articleId;
	}
	
	/**
	 * 文章发布信息存入数据库 用于计划任务同步FTP
	 * @param Int $articleId
	 * @param  Array $synchroArr 同步数据
	 */
	public function articlePublishSynchro($articleId, $synchroArr){
		
		$sql = "delete from `ArticlePublish` where ArticleId=%s";
		$this->query($sql,array($articleId));

		$sql = "insert into `ArticlePublish` (ArticleId,LocalFileName,TagDomain) values";
		$sqlArr = $valArr = array();
		foreach($synchroArr as $arr){
			array_push($sqlArr,'(%s,%s,%s)');
			array_push($valArr,$arr['articleId']);
			array_push($valArr,$arr['localFileName']);
			array_push($valArr,$arr['topTagDomain']);
		}
		$sql .= implode(',',$sqlArr);
		$this->query($sql,$valArr);
	}
	
	/**
	 * 获取图片进入浏览模式图片ID（目前使用老库文章关联图片ID）
	 * @param unknown $oldArticleId
	 */
	public function getPicBrowse($oldArticleId){
		
		$this->initOldDB();
		$sql="select id from `content_photo` where article_id=%s and disrel=0 order by id asc limit 1";
		return $this->query($sql,array($oldArticleId))->fetch_assoc();
	}
	/**
	 * 添加文章关系表
	 *
	 * @param \haibao\cms\model\data\Article $articleModel
	 * @param bool $isAdd
	 */
	private function addArticleRelationTable($articleModel, $isAdd = true) {
		$isEdit = true;
		if($isAdd){
			$isEdit = false;
		}
		$this->addArticleTag ( $articleModel->ArticleTag, $articleModel->Id, $isEdit );
		
		$this->addImageCollectiveArticle($articleModel->ArticleImageCollective,$articleModel->Id);
		
		$contentPageIdArr = $this->addArticleContent ( $articleModel->ArticleContent, $articleModel->Id, $isEdit );
	
		$this->addArticleProduct ( $articleModel->ArticleProduct, $articleModel->Id, $contentPageIdArr, $isEdit );
		
		$this->addArticleImage ( $articleModel->ArticleImage, $articleModel->Id, $contentPageIdArr, $isEdit );
	
		//if($isAdd){
			$this->addArticleProImage ( $articleModel->ArticleProImage, $articleModel->Id);
		//}
	
		if ($isAdd) {
			$articleModel->ArticleProperty = new \haibao\cms\model\data\ArticleProperty();
			$articleModel->ArticleProperty->ArticleId = $articleModel->Id;
			$articleModel->ArticleProperty->ClickNum = 0;
			$articleModel->ArticleProperty->CommentNum = 0;
			$articleModel->ArticleProperty->VoteNum = 0;
			$articleModel->ArticleProperty->EditClickNum = 0;
			$this->add ( $articleModel->ArticleProperty );
		}
	}
	public  function addImageCollectiveArticle($articleImageCollectiveModel,$articleId){	
			
		$sql="delete from ImageCollectiveArticle where ArticleId = %s";
		$this->query($sql,array($articleId));	
		if($articleImageCollectiveModel){
			$articleImageCollectiveModel->ArticleId = $articleId;
			$this->add($articleImageCollectiveModel);
		}
	}
	
	private function addArticleProperty($articlePropertyModel, $articleId) {
		$articlePropertyModel->ArticleId = $articleId;
		$this->add ( $articlePropertyModel );
	}
	private function addArticleProImage($articleProImageModels, $articleId) {
		$sql = "select Id from ArticleProImage where ArticleId = %s AND level =0 limit 1";
		$result = $this->query($sql,array($articleId))->fetch_assoc();
		if ($articleProImageModels && !$result) {
			foreach ( $articleProImageModels as $key => $proImageModel ) {
				$proImageModel->ArticleId = $articleId;
				$articleTagModels [$key] = $proImageModel;
			}
		}
		if ($articleProImageModels) {
			$this->addAll ( $articleProImageModels );
		}
	}
	
	private function addArticleTag($articleTagModels, $articleId, $isEdit = false) {
		if ($isEdit) {
			$sql = 'delete from ArticleTag where ArticleId=%s';
			$this->query ( $sql, array (
					$articleId 
			) );
		} 
		if ($articleTagModels) {
			foreach ( $articleTagModels as $key => $tagModel ) {
				if($tagModel->TagId){
					$tagModel->ArticleId = $articleId;
					$articleTagModels [$key] = $tagModel;
				}else{
					unset($articleTagModels [$key]);
				}
			}
		}
		if ($articleTagModels) {
			$this->addAll ( $articleTagModels );
		}
	}
	private function addArticleContent($articleContentModels, $articleId, $isEdit = false) {
		$contentPageIdArr = array ();
		if ($isEdit) {
			$sql = 'delete from ArticleContent where ArticleId=%s';
			$this->query ( $sql, array (
					$articleId 
			) );
		}
		if ($articleContentModels) {
			foreach ( $articleContentModels as $key => $contentModel ) {
				if($contentModel->Content){
					$contentModel->ArticleId = $articleId;
					$this->add ( $contentModel );
					$contentPageIdArr [$contentModel->CurrentPage] = $contentModel->Id;
				}
			}
		}
		
		return $contentPageIdArr;
	}
	private function addArticleProduct($articleProductModels, $articleId, $contentPageIdArr, $isEdit = false) {
		if ($isEdit) {
			$sql = 'delete from ArticleProduct where ArticleId=%s';
			$this->query ( $sql, array (
					$articleId 
			) );
		}
		
		if ($articleProductModels) {
			foreach ( $articleProductModels as $key => $productModel ) {
				$productModel->ArticleId = $articleId;
				if (! empty ( $contentPageIdArr [$productModel->CurrentPage] )) {
					$productModel->ArticleContentId = $contentPageIdArr [$productModel->CurrentPage];
				}
				$articleProductModels [$key] = $productModel;
			}
			$this->addAll ( $articleProductModels );
		}
	}
	private function addArticleImage($articleImageModels, $articleId, $contentPageIdArr, $isEdit = false) {
		if ($isEdit) {
			$sql = 'delete from ArticleImage where ArticleId=%s';
			$this->query ( $sql, array (
					$articleId 
			) );
		}
		
		if ($articleImageModels) {
			foreach ( $articleImageModels as $key => $imageModel ) {
				$imageModel->ArticleId = $articleId;
				if (! empty ( $contentPageIdArr [$imageModel->CurrentPage] )) {
					$imageModel->ArticleContentId = $contentPageIdArr [$imageModel->CurrentPage];
				}
				$articleImageModels [$key] = $imageModel;
			}
			$this->addAll ( $articleImageModels );
		}
	}
	public function getArticleAppCloumn($articleId){
			$sql = 'select `column_id` from `AppArticleCategory` where `document_id`=%s';
			$result = $this->query ( $sql, array ($articleId));
			$appCloumn = array();
			while ($result->fetch_assoc()){
			   array_push($appCloumn, $result->getData('column_id'));
		    }
		    return $appCloumn;
	}
	
	/**
	 * 通过文章ID得到它的主标签ID
	 * @param array $articleIds
	 * @return array(Article=>TagId)
	 */
	public function getArticlePrimaryTag($articleIds){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql = "select `ArticleId`,`TagId` from `ArticleTag` where `ArticleId` in (".$str.") and `IsPrimaiy` =1";
		$result = $this->query($sql, $articleIds);
		$primaryTag = array();
		while ($result->fetch_assoc()){
			$primaryTag[$result->getData('ArticleId')] = $result->getData('TagId');
		}
		return $primaryTag;
	}
	
	public function getPublishedArticleIds($articleIds){
		$articleFilter = new ArticleFilter();
		$articleFilter->select(array(ArticleFilter::CONDITION_FIELD_NAME_ID));
		$articleFilter->where(ArticleFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_IN, $articleIds);
		$articleFilter->where(ArticleFilter::CONDITION_FIELD_NAME_PUBLISHED, Condition::CONDITION_EQUAL, \haibao\cms\model\data\Article::PUBLISHED_YES);
		$result = $this->getAll($articleFilter);
		$Ids = array();
		if($result){
			foreach($result as $article){
				array_push($Ids, $article->Id);
			}
		}
		return $Ids;
	}
	
	public function getOldAticleId($articleIds,$isNewId = true){
		$oldArticleIds = array();
		$str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql="select OldPrimaryKey,PrimaryKey from DataMigrationMap where ";
		$where = " TableName = 'Article' and PrimaryKey in (".$str.")";
		if(!$isNewId){
			$where = " TableName = 'Article' and OldPrimaryKey in (".$str.")";
		}
		$result = $this->query($sql.$where, $articleIds);
		$primaryTag = array();
		while ($result->fetch_assoc()){
			$oldArticleIds[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
		}
		if(!$isNewId){
			$oldArticleIds = array_flip($oldArticleIds);
		}
		return $oldArticleIds;
	}
	
	public function getNewImgId($oldImgIds){
		$newImgIdArr = array();
		$str = preg_replace('/(\d+)/', '%s', implode(',', $oldImgIds));
		$sql="select PrimaryKey from DataMigrationMap where TableName = 'ImageLibrary' and OldPrimaryKey in (".$str.")";
		$result = $this->query($sql, $oldImgIds);
		while ($result->fetch_assoc()){
			if(!in_array($result->getData('PrimaryKey'), $newImgIdArr)){
				$newImgIdArr[] = $result->getData('PrimaryKey');
			}
		}
		return $newImgIdArr;
	}
	
	public function getQueryResult($query){
		return $this->getAll($query);
	}
	
	/**
	 * **********************文章老数据通过方法 start*********************************
	 */
	/**
	 * 添加老文章
	 */
	public function addOldArticleData($articleModel) {
		$this->initOldDB ();
		//操作document_index 获取document_id(为第一个的文章ID)
		$articleModel->ArticleOldID = $this->getNewDocumentId ();
		$this->saveContentCopy ( $articleModel );
		$this->saveOldArticleContentFirst ( $articleModel );
		
		$this->initNewDB ();
		$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
		$sql .= "values('".$articleModel->getTableName()."','".$articleModel->Id."','" . $articleModel->ArticleOldID . "')";
		$this->query ( $sql );
		
		$this->initOldDB ();
		if ($articleModel->SiteType == \haibao\cms\model\data\Article::SITETYPE_ARTICLE) {
			//处理另外几页文章内容
			unset ( $articleModel->ArticleContent [0] );
			if(!empty($articleModel->ArticleContent)){
				$this->saveOldArticleContentOther ( $articleModel );
			}
		}
		//文章关联产品处理
		$this->saveOldArticleProduct ( $articleModel->ArticleOldID, $articleModel->ArticleProduct );
		//文章关联标签处理
		$cateId = $this->saveOldArticleTag ( $articleModel, $articleModel->ArticleOldID );

		//文章关联图片
		$this->saveOldArticleImg ( $articleModel, $articleModel->ArticleOldID );

		//文章关联到导读图
		$this->saveOldDisRelImg($articleModel,$articleModel->ArticleOldID);
		
		//文章添加顶级标签
		$sql = "update doc_index set cateid = %s WHERE document_id=%s OR rootid=%s";
		$this->query($sql,array($cateId, $articleModel->ArticleOldID,$articleModel->ArticleOldID));
		$sql = "update rel_doc_tag set cateid = %s , rstatus = %s , rpublished = %s , rpic_num = %s,rpriority = %s ,rdataorder = %s WHERE document_id=%s";
		$this->query($sql,array(
				$cateId,				
				$articleModel->Status,
				$articleModel->Published,
				$articleModel->PicCount,
				$articleModel->Level,
				strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')),
				$articleModel->ArticleOldID
			)
		);	
		
		if($articleModel->AppColum){
			$this->addArticleToApp($articleModel,true);
		}
		
		return $articleModel;
	}
	
	
	
	/**
	 * 修改老文章
	 */
	private function updateOldArticleData($articleModel) {
		// 获取老的文章ID
		$this->initNewDB();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey =%s';
		$result = $this->query($sql,array('Article',$articleModel->Id))->fetch_assoc();
		$documentId = $result['OldPrimaryKey'];
		//没有找到新-老关系对应记录
		if(empty($documentId)) return NULL;
		$articleModel->ArticleOldID=$documentId;
		$this->initOldDB ();
		$this->saveContentCopy ( $articleModel );
		$this->saveOldArticleContentFirst($articleModel, true);
		if ($articleModel->SiteType == \haibao\cms\model\data\Article::SITETYPE_ARTICLE) {
			//处理另外几页文章内容
			unset ( $articleModel->ArticleContent [0] );
			if(!empty($articleModel->ArticleContent)){
				$this->saveOldArticleContentOther ($articleModel);
			}
		}

		$this->saveOldArticleProduct ( $documentId, $articleModel->ArticleProduct );
		
		$cateId = $this->saveOldArticleTag ( $articleModel, $documentId );
		
		$this->saveOldArticleImg ( $articleModel, $documentId );
		
		$this->saveOldDisRelImg($articleModel,$documentId);
		
		//文章添加顶级标签
		$sql = "update doc_index set cateid = %s WHERE document_id=%s OR rootid=%s";
		$this->query($sql,array($cateId, $documentId,$documentId));
		
		$sql = "update rel_doc_tag set cateid = %s , rstatus = %s , rpublished = %s , rpic_num = %s,rpriority = %s ,rdataorder = %s WHERE document_id=%s";
		$this->query($sql,array(
				$cateId,				
				$articleModel->Status,
				$articleModel->Published,
				$articleModel->PicCount,
				$articleModel->Level,
				strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')),
				$articleModel->ArticleOldID
			)
		);
		if($articleModel->AppColum){
			$this->addArticleToApp($articleModel,true);
		}
		
	}

	/**
	 * 备份文章数据
	 * @param : Int $documentId 文章ID
	 * @param : Object \haibao\cms\model\data\ArticleModel
	 */
	private function saveContentCopy( $articleModel ) {			
			$sql = "INSERT INTO `haibao_article`.`content_recover` (
    		`document_id` ,
    		`content` ,
    		`date`
    		)
    		VALUES (%s,%s,%s)";
			$valArr = array ();
			array_push ( $valArr, $articleModel->ArticleOldID );
			array_push ( $valArr, $articleModel->Content );
			array_push ( $valArr,date('Y-m-d H:m:i'));
			$this->query ( $sql, $valArr );
	}
	
	/**
	 * 添加文章第一页内容（组图资讯/普通资讯）
	 * @param : Object \haibao\cms\model\data\Article
	 * @param : Int $documentId 文章父ID
	 */
	private function saveOldArticleContentFirst($articleModel,$isEdit = false) {
		$valArr = array ();
		if(!$isEdit){
			$sql = "insert into `doc_index` (`document_id`,`title`,`second_title`,`digest`,`Author`,`username`,`lastusername`,`priority`,`is_fee`,`producer_link`,`pic_source`,`article_source`,`date`,`dateorder`,`published`,`doc_type`,`sitetype`,`pic_num`) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)";
			array_push ( $valArr, $articleModel->ArticleOldID );
			array_push ( $valArr, $articleModel->Title );
			array_push ( $valArr, $articleModel->ShortTitle );
			array_push ( $valArr, $articleModel->Summary );
			array_push ( $valArr, \haibao\cms\business\Article::getCurrentUser()->RealName);
			array_push ( $valArr, $articleModel->Author );
			array_push ( $valArr, $articleModel->Author );
			array_push ( $valArr, $articleModel->Level);
			array_push ( $valArr, $articleModel->IsPseudonym );
			array_push ( $valArr, $articleModel->ArticleSource );
			array_push ( $valArr, '');
			array_push ( $valArr, $articleModel->ArticleSource );
			array_push ( $valArr, $articleModel->CreateTime->format( 'Y-m-d H:i:s'));
			array_push ( $valArr, $articleModel->PublishTime);
			array_push ( $valArr, $articleModel->Published );
			array_push ( $valArr, $articleModel->SiteType + 1);
			array_push ( $valArr, $articleModel->SiteType );
			array_push ( $valArr, $articleModel->PicCount );
			$this->query ( $sql, $valArr );
			if ($articleModel->SiteType == 0) {
				$content = '';
				if($articleModel->ArticleContent){
					$content = $articleModel->ArticleContent[0]->Content;
				}
				//普通文章内容入库
				$tableName = $this->createContentTable ( $articleModel->ArticleOldID );
				$sql = "insert into $tableName (document_id,content) values (%s,%s) ";
				$this->query ( $sql, array (
						$articleModel->ArticleOldID,
						$content
				) );
			} else {
				//组图文章入图片库
				$sql = "insert into content_images (document_id,content) values (%s,%s)";
				$this->query ( $sql, array (
						$articleModel->ArticleOldID,
						addslashes ( $articleModel->ArticleContent ) 
				) );
			}
			
		}else{
			$sql = 'update doc_index  set `title` = %s,`second_title` = %s,`digest` = %s,`lastusername` = %s,`priority` = %s,`is_fee` = %s,`producer_link` = %s,`pic_source` = %s,`article_source` = %s,`date` = %s,`dateorder` = %s,`published` = %s,`doc_type`= %s,`sitetype`= %s,`pic_num`= %s where document_id = %s';
			array_push ( $valArr, $articleModel->Title);
			array_push ( $valArr, $articleModel->ShortTitle );
			array_push ( $valArr, $articleModel->Summary );
			array_push ( $valArr, $articleModel->Author );
			array_push ( $valArr, $articleModel->Level);
			array_push ( $valArr, $articleModel->IsPseudonym );
			array_push ( $valArr, $articleModel->ArticleSource );
			array_push ( $valArr, '');
			array_push ( $valArr, $articleModel->ArticleSource );
			array_push ( $valArr, date('Y-m-d H:m:i'));
			array_push ( $valArr, $articleModel->PublishTime);
			array_push ( $valArr, $articleModel->Published );
			array_push ( $valArr, $articleModel->SiteType + 1);
			array_push ( $valArr, $articleModel->SiteType );
			array_push ( $valArr, $articleModel->PicCount );
			array_push ( $valArr, $articleModel->ArticleOldID );
			$this->query ( $sql, $valArr );
			
			if ($articleModel->SiteType == 0) {
			
				//普通文章内容入库
				$tableName = "content_".floor($articleModel->ArticleOldID/10000);
				$sql = "update  $tableName set  content = %s where document_id = %s";
				$this->query ( $sql, array (
						$articleModel->ArticleContent[0]->Content,
						$articleModel->ArticleOldID,
				) );
				
				//删除原有文章信息
				$sql = 'select document_id from `doc_index` where fatherid=%s and rootid=%s';
				$result = $this->query($sql,array($articleModel->ArticleOldID,$articleModel->ArticleOldID));
				$documentIdArr = array();
				while($result->fetch_assoc()){
					$documentIdArr[] = $result->getData('document_id');
					$tableName = "content_".floor($result->getData('document_id')/10000);
					$sql = "delete from $tableName where document_id = %s";
					$this->query($sql,array($result->getData('document_id')));
				}
				
				if($documentIdArr){
					$sql = 'delete from `doc_index` where fatherid=%s and rootid=%s';
					$this->query($sql,array($articleModel->ArticleOldID,$articleModel->ArticleOldID));
				}
			} else {
				//组图文章入图片库
				$sql = "update content_images set content =%s where document_id = %s";
				$this->query ( $sql, array (
						addslashes ( $articleModel->ArticleContent ),
						$articleModel->ArticleOldID,
				) );
			}
		}
	}
	/**
	 * 添加文章分页内容
	 * @param : String $content
	 * @param : Int $documentId 文章父ID
	 * @param : Object $articleModel 
	 */
	private function saveOldArticleContentOther($articleModel) {
		$valArr = array();
		$contentArr = array();
		$contentLoop=array();
		$pid=0;
		$docSql = "insert into `doc_index` (`document_id`,`title`,`digest`,`Author`,`username`,`lastusername`,`priority`,`producer_link`,`date`,`dateorder`,`published`,`doc_type`,`sitetype`,`pic_num`,`rootid`,`fatherid`) values ";
		foreach( $articleModel->ArticleContent as $key =>$Content){
			$pid = $this->getNewDocumentId ();			
			$contentTableName = $this->createContentTable ( $pid );			
			$contentLoop[$contentTableName][$pid]=$Content;
			$docSql.="(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s),";
			array_push($valArr,$pid);
			array_push($valArr,$articleModel->Title);
			array_push($valArr,$articleModel->Summary);
			array_push($valArr,$articleModel->Author);
			array_push($valArr,$articleModel->Author);
			array_push($valArr,$articleModel->Author);
			array_push($valArr,$articleModel->Level);
			array_push($valArr,$articleModel->ArticleSource);
			array_push($valArr,$articleModel->CreateTime->format( 'Y-m-d H:i:s'));
			array_push($valArr,$articleModel->PublishTime);
			array_push($valArr,0);
			array_push($valArr,$articleModel->SiteType + 1);
			array_push($valArr,$articleModel->SiteType);
			array_push ( $valArr, $articleModel->PicCount );
			array_push ( $valArr, $articleModel->ArticleOldID );
			array_push ( $valArr, $articleModel->ArticleOldID );
			
		}
		$docSql=rtrim($docSql,',');
		$this->query ( $docSql, $valArr );
			
		//普通文章内容入库,因为表名是变化的,暂时没想到更好的办法
		foreach ( $contentLoop as $key => $content ) {
			$contentSql = "insert into $key (document_id,content) values ";
			foreach ( $content as $k => $value ) {
				$contentSql .= "(%s,%s),";
				array_push ( $contentArr, $k );
				array_push ( $contentArr, $value->Content );
			}
			$contentSql = rtrim ( $contentSql, ',' );
			$this->query ( $contentSql, $contentArr );
		}
	
	}
	
	private function createContentTable($documentId) {
		$tableName = "content_" . floor ( $documentId / 10000 );
		$sql = "CREATE TABLE IF NOT EXISTS $tableName (
    	document_id int(11) DEFAULT '0' NOT NULL,
    	content mediumtext NOT NULL,
    	PRIMARY KEY (document_id))";
		$this->query ( $sql );
		return $tableName;
	}
	
	/**
	 * @param Int $documentId 文章父Id
	 * @param Array $products        	
	 */
	private function saveOldArticleProduct($documentId, $products) {
		$sql = "delete from `doc_index_product_ids` where `document_id` = %s";
		$this->query ( $sql, array (
				$documentId
		) );
		
		$productIdArr = $oldProductIdArr = array ();
		if ($products) {
			
			foreach ( $products as $product ) {
				$productIdArr [] = $product->ProductId;
			}
			$this->initNewDB();
			$sql = 'select * from `DataMigrationMap` where TableName=%s and PrimaryKey in ('.implode(',',$productIdArr).')';
			$result = $this->query($sql,array('ProductModel'));
			while($result->fetch_assoc()){
				$oldProductIdArr[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
			}
			
			if($oldProductIdArr){
				$this->initOldDB();
				$sqlArr = $valArr = array ();
				$sql = "insert into `doc_index_product_ids` (`document_id`,`product_id`) values ";
				foreach ( $productIdArr as $id ) {
					if(!empty($oldProductIdArr[$id])){
						array_push ( $sqlArr, '(%s,%s)' );
						array_push ( $valArr, $documentId, $oldProductIdArr[$id] );
					}
				}			
				$sql .= implode ( ',', $sqlArr );
				$this->query ( $sql, $valArr );
			}
		}
	}
	
	private function delOldArticleTag($articleId,$tagId){
		$sql="select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s ";
		$articleResult = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		if($articleResult){
			$this->initOldDB ();
			$sql = 'delete from rel_doc_tag where document_id=%s and tag_id=%s';
			$this->query ( $sql, array ($articleResult['OldPrimaryKey'],$tagId ));
		}
	}
	
	/**
	 * 文章关联标签处理
	 */
	private function saveOldArticleTag($articleModel, $documentId,$isAdd = true) {
		$cateId = "";
		$this->initOldDB ();
		if($isAdd){
			//删除文章原始标签
			$sql = 'delete from rel_doc_tag where document_id=%s';
			$this->query ( $sql, array ($documentId ) );
		}
		$valArr = $sqlArr = array ();
		if ($articleModel->ArticleTag) {
			$sql = 'insert into rel_doc_tag(document_id,tag_id,istpl,suser,lastmodified,rpriority,rpic_num,rdataorder,rpublished,rdoc_type,rsitetype,rstatus) values ';
			foreach ( $articleModel->ArticleTag as $tag ) {

				if($tag->TagId ){
					array_push ( $sqlArr, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' );
					array_push ( $valArr, $documentId );
					array_push ( $valArr, $tag->TagId );
					array_push ( $valArr, $tag->IsPrimaiy );
					array_push ( $valArr, $articleModel->Author );
					array_push ( $valArr, time() );
					array_push ( $valArr, $articleModel->Level );
					array_push ( $valArr, $articleModel->PicCount );
					array_push ( $valArr, strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')));
					array_push ( $valArr, $articleModel->Published );
					array_push ( $valArr, $articleModel->SiteType + 1 );
					array_push ( $valArr, $articleModel->SiteType );
					array_push ( $valArr, $articleModel->Status );
					if($tag->IsPrimaiy == 1){
						$cateId = $tag->ParentId;
					}
				}
			}
			if($valArr){
			$sql .= implode ( ',', $sqlArr );
			$this->query ( $sql, $valArr );
			}
		}
		
		//投票
		$voteNum = 0;
		$sqlArr = array();
		$valArr = array();
		$sql="select count(id) as count from vote_newvote where article_id = %s ";
		$result = $this->query ( $sql, array($documentId) );
		while($result->fetch_assoc()){
			$voteNum = $result->getData('count');
		}
		if($voteNum){
			$sql = "REPLACE into rel_doc_tag (document_id,tag_id,istpl,suser,lastmodified,rpriority,rpic_num,rdataorder,rpublished,rdoc_type,rsitetype,rstatus) 
			values ";
			
			array_push ( $sqlArr, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' );
			array_push ( $valArr, $documentId );
			array_push ( $valArr, '2713' );
			array_push ( $valArr, '0' );
			array_push ( $valArr, $articleModel->Author );
			array_push ( $valArr, time() );
			array_push ( $valArr, $articleModel->Level );
			array_push ( $valArr, $articleModel->PicCount );
			array_push ( $valArr, strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')));
			array_push ( $valArr, $articleModel->Published );
			array_push ( $valArr, $articleModel->SiteType + 1 );
			array_push ( $valArr, $articleModel->SiteType );
			array_push ( $valArr, $articleModel->Status );
			$sql.=join(',',$sqlArr);
			$result = $this->query ( $sql, $valArr );
			
		}
		
		//处理无结构标签
		$sql = "select tag_id, tag_name,alias from tag where parent_id=6 and tag_status=1";
		$result = $this->query ( $sql );
		while ( $result->fetch_assoc () ) {
			
			$tagId = $result->getData ( 'tag_id' );
			$aliasStr = str_replace ( '，', ',', $result->getData ( 'alias' ) );
			$aliasArr = explode ( ',', $aliasStr );
			$aliasArr [] = $result->getData ( 'tag_name' );
			if ($aliasArr) {
				$aliasArr = array_filter ( $aliasArr );
				foreach ( $aliasArr as $key => $tagName ) {
					if (strpos ( $articleModel->Title, $tagName ) !== false) {
						$sql = "select document_id from `rel_doc_tag` where document_id=%s and tag_id=%s";
						$data = $this->query ( $sql, array (
								$documentId,
								$tagId 
						) )->fetch_assoc ();
						
						if (! $data) {
							$sql = 'replace into rel_doc_tag(document_id,tag_id,istpl,suser,lastmodified,rpriority,rpic_num,rdataorder,rpublished,rdoc_type,rsitetype,rstatus) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)';
							
							$this->query ( $sql, 
								array (
									$documentId,
									$tagId,
									0,
									$articleModel->Author,
									strtotime($articleModel->CreateTime->format('Y-m-d H:i:s')) ,
									$articleModel->Level,
									$articleModel->PicCount,
									strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')),
									$articleModel->Published,
									$articleModel->SiteType + 1,
									$articleModel->SiteType,
									$articleModel->Status
								)
							);
						}
					}
				}
			}
		}
		return $cateId;
	}
	
	/**
	 * 文章关联图片
	 * @param : Object \haibao\cms\model\data\Article
	 * @param : Int $documentId
	 * @table : content_photo
	 */
	private function saveOldArticleImg($articleModel, $documentId) {
		if(empty($articleModel->ArticleImage)) return "";
		$articleImages = $this->getImageRel($articleModel->ArticleImage);
		$articleModel->ArticleOldImageId=$articleImages;
		$this->initOldDB();
		$sql = 'delete from `content_photo` where article_id = %s and disrel = 0';
		$this->query ( $sql, array ($documentId) );
		if($articleImages){
			$valArr = $sqlArr = array ();
			$sql = "INSERT INTO `content_photo` (`image`,`date`,`article_id`,`title`,`blog_id`,`origin_url`,`pic_id`,`width`,`height`,`sitetype`) VALUES ";
			foreach ( $articleImages as $key => $image ) {
				array_push ( $sqlArr, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)');
				array_push ( $valArr, ltrim($image->PicUrl, '/') );
				array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
				array_push ( $valArr, $documentId );
				array_push ( $valArr, $image->Description );
				array_push ( $valArr, 0 );
				array_push ( $valArr, ltrim($image->PicUrl, '/') );
				array_push ( $valArr, (string)$image->ImageId );
				array_push ( $valArr, $image->Width );
				array_push ( $valArr, $image->Height );
				array_push ( $valArr, $articleModel->SiteType );
			}
			$sql .=implode(',',$sqlArr);
			$this->query ( $sql, $valArr );
		}
		
// 		$this->addPicTag ($documentId );
// 		$this->modifyPicTag ( $key, $this->getDb ()->insert_id, $documentId );
		
		$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = 0 ';
		$this->query ( $sql, array ($documentId ) );
		
		if($articleImages){
			$imageArr = $sqlArr = $valArr = array();
			$sql = "INSERT INTO `picsm_pic_obj` (`module_id` ,`obj_id` ,`pic_id`,`disrel`,`adddate`,`is_order`) VALUES ";
			foreach ( $articleImages as $key => $image ) {
				if(!in_array($image->ImageId, $imageArr)){//图片去重
					array_push ( $sqlArr, '(%s,%s,%s,%s,%s,%s)');
					array_push ( $valArr, 1 );
					array_push ( $valArr, $documentId );
					array_push ( $valArr, $image->ImageId );
					array_push ( $valArr, 0 );
					array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
					array_push ( $valArr, $key + 1 );
					$imageArr[]=	$image->ImageId;
				}
			}
			$sql .= implode(',',$sqlArr);
			$this->query ( $sql, $valArr );
		}
	}
	
	/**
	 * 文章添加导读图
	 */
	private function saveOldDisRelImg($articleModel,$documentId){
		if(empty($articleModel->ArticleProImage)) return "";
		$articleImages = $this->getImageRel($articleModel->ArticleProImage);
		
		$this->initOldDB();
		$sql = 'delete from `content_photo` where article_id = %s and disrel !=0';
		$this->query($sql,array($documentId));
		
		if($articleImages){
			$imageArr = $valArr = $sqlArr = array();
			$sql = "INSERT INTO `content_photo` (`image`,`date`,`article_id`,`origin_url`,`pic_id`,`width`,`height`,`disrel`,`sitetype`) VALUES ";
			foreach($articleImages as $key=>$image){
				array_push($sqlArr, ' (%s,%s,%s,%s,%s,%s,%s,%s,%s)');
				array_push ( $valArr, ltrim($image->PicUrl, '/') );
				array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
				array_push ( $valArr, $documentId );
				array_push ( $valArr, ltrim($image->PicUrl, '/') );
				array_push ( $valArr, $image->ImageId );
				array_push ( $valArr, $image->Width );
				array_push ( $valArr, $image->Height );
					
				if($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
					if($image->Level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
						array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_SET_PRO_IMG_TYPE );
					}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_ONE){
						array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3 );
					}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_TWO){
						array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1 );
					}else{
						array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7 );
					}
				}elseif($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_COVER){
					array_push ( $valArr, 2 );
				}
				array_push ( $valArr, $articleModel->SiteType );
			}
			$sql .= implode(',',$sqlArr);
			$this->query ( $sql, $valArr );
		}
		
		
		$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and disrel !=0';
		$this->query($sql,array($documentId));
		
		if($articleImages){
			$sql = "INSERT INTO `picsm_pic_obj` (`module_id` ,`obj_id` ,`pic_id`,`disrel`,`adddate`,`is_order`) VALUES ";
			$valArr = $sqlArr = array();
			foreach($articleImages as $key=>$image){
			
				if(!in_array($image->ImageId, $imageArr)){//鍥剧墖鍘婚噸
					array_push($sqlArr, '(%s,%s,%s,%s,%s,%s)');
					array_push ( $valArr, 1 );
					array_push ( $valArr, $documentId );
					array_push ( $valArr, $image->ImageId );
			
					if($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
						if($image->Level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_SET_PRO_IMG_TYPE );
						}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_ONE){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3 );
						}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_TWO){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1 );
						}else{
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7 );
						}
					}elseif($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_COVER){
						array_push ( $valArr, 2 );
					}
			
					array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
					array_push ( $valArr, $key+1 );
					$imageArr[] = $image->ImageId;
				}
			}
			$sql .= implode(',',$sqlArr);
			$this->query ( $sql, $valArr );
		}
		
	}
	
	/**
	 * 给新加的图片添加跟老图一样的图片标签 (新图跟老图同一个ID 自增长ID不同)
	 * @param Int $picId 图片ID
	 * @param Int $contentPhotoId content_photo 自增长ID
	 * @param Int $documentId 文章ID
	 */
	private function addPicTag($documentId = 0) {
		$picIdArr=array();
		$contentPhotoIdArr=array();
		$dbPhotoIdArr = array();	
		$picIds='';
		$contentPhotoIds='';
		$dbPhotoIds='';
		$i=0;
		$tagsArr = array();
		$sql="select pic_id,id from content_photo where article_id  = %s ";
		$result = $this->query($sql,array($documentId));
		while($result->fetch_assoc()){
			$picIdArr[] = $result->getData ( 'pic_id' );
			$contentPhotoIdArr[] = $result->getData ( 'id' );
		}
		
	
		// 查出相同pic_id的content_photo_id
		if($picIdArr) $picIds = join(',', $picIdArr);
		if($contentPhotoIdArr) $contentPhotoIds = join(',', $contentPhotoIdArr);
		$sql = "select id from content_photo where pic_id = %s and id <> %s order by id limit 1";
		$result = $this->query ( $sql,array($picIds[0],$contentPhotoIds[0]));
		while ( $result->fetch_assoc () ) {
			$dbPhotoIdArr[] = $result->getData ( 'id' );
		}
		if ($dbPhotoIdArr ) {
			$dbPhotoIds = $dbPhotoIdArr[0];
			$sql = "select photo_id,articleclass_id,istpl from content_photo_tags where photo_id in ( %s )";
			$r = $this->query ( $sql, array ($dbPhotoIds) );			
			while ( $r->fetch_assoc () ) {
				$tagsArr[]['photo_id']=$r->getData('photo_id');
				$tagsArr[]['articleclass_id']=$r->getData('articleclass_id');
				$tagsArr[]['istpl']=$r->getData('istpl');				
			}
			if($tagsArr){
				$sql="insert into `content_photo_tags` (`photo_id`,`articleclass_id`,`document_id`,`istpl`,`pic_id`) values ";
				foreach ( $tagsArr as $key => $tags ) {
					array_push($sqlval,  '(%s,%s,%s,%s,%s)');
					array_push($array, $tags['photo_id']);
					array_push($array, $tags['articleclass_id']);
					array_push($array, $documentId);
					array_push($array, $tags['istpl']);
					array_push($array, $picIds[0]);
				}
				$insertTag=$this->query($sql,$array);
			}
			
		}
	}
	
	/**
	 * 删除文章图片信息
	 * @param : $documentId 文章ID
	 */
	private function deleteOldArticleImg($documentId) {
		$sql = "DELETE FROM `content_photo` WHERE `article_id` = %s and `disrel` = 0 ";
		$this->query ( $sql, array ($documentId ) );
		
		$sql = "select pic_id from `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = 0 ";
		$result = $this->query ( $sql, array ($documentId ) );
		$picIdArr = array ();
		while ( $result->fetch_assoc () ) {
			$picIdArr [] = $result->getData ( 'pic_id' );
		}
		
		if ($picIdArr) {
			$sql = "DELETE FROM `picsm_pic_index` where pic_id in (" . implode ( ",", $picIdArr ) . ")";
			$this->query ( $sql );
		}
		
		$sql = "DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = 0 ";
		$this->query ( $sql, array ($documentId ) );
	}
	
	// 标签补丁
	private function modifyPicTag($picId, $contentPhotoId, $documentId = 0) {
		$sql = "select * from `content_photo_tags` where pic_id = %s and `photo_id` = 0 order by id limit 1";
		$result = $this->query ( $sql, array ($picId ) )->fetch_assoc ();
		if ($result) {
			$sql = "update `content_photo_tags` set `photo_id`=%s where pic_id = %s and `photo_id` = 0 ";
			$this->query ( $sql, array ($contentPhotoId,$picId ) );
		}
	}
	
	/**
	 * 取得最新的符合规范的文章ID
	 */
	private function getNewDocumentId() {
		$sql = "select max(document_id) as documentId from doc_index";
		$result = $this->query ( $sql );
		while ( $result->fetch_assoc () ) {
			
			$maxId = $result->getData ( 'documentId' );
		}
		$id = $this->createDocumentId ();
		while ( $id < $maxId + 1 ) {
			$id = $this->createDocumentId ();
		}
		return $id;
	}
	
	/**
	 * 生成一个新的文章ID
	 */
	private function createDocumentId() {
		$sql = "insert into document_index (class_id) values ('0')";
		$this->query ( $sql );
		return $this->getDb ()->insert_id;
	}
	

	private function initNewDB() {
		$this->setConfig ( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		return $this;
	}
	private function initOldDB() {
		$this->setConfig ( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		return $this;
	}

	/**
	 * 获取图片新老数据关联关系
	 * @param : $articleImages 文章图片
	 */
	private function getImageRel($articleImages){
		$imageIdRel=$imageIdArr = $contentImgArr = array();
		foreach($articleImages as $img){
			$imageIdArr[] = $img->ImageId;
		}
		$imageIdArrs = array_unique($imageIdArr);
		if($imageIdArrs){
			// 查询出老库的图片Id
			$this->initNewDB();
			$sql = 'select PrimaryKey,OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey in ('.implode(',',$imageIdArr).')';
			$result = $this->query($sql,array('ImageLibrary'));
			while ($result->fetch_assoc()){
				$imageIdRel[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
			}
			if($articleImages && $imageIdRel){
				foreach ($articleImages as $key => $image ) {
					if(!empty($imageIdRel [$image->ImageId])){
						$image->ImageId = $imageIdRel [$image->ImageId];
					}
					$contentImgArr [] = $image;
				}
			} elseif($articleImages){
				foreach ($articleImages as $key => $image ) {
					$contentImgArr [] = $image;
				}
			}
		}
			
		return 	$contentImgArr;	
	}
	/**
	 * 修改老文章状态
	 */
	private function updateOldArticleStatus($articleId, $status) {
		$articleModel = new \haibao\cms\model\data\Article ();
		$tableName = $articleModel->getTableName ();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="' . $tableName . '" and PrimaryKey =%s';
		$result = $this->query ( $sql, array (
				$articleId 
		) );
		$oldArticleId = 0;
		while ( $result->fetch_assoc () ) {
			$oldArticleId = $result->getData ( 'OldPrimaryKey' );
		}
		if ($oldArticleId) {
			$this->setConfig ( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			
			$sql = 'update doc_index set status=%s where document_id=%s or rootid=%s';
			$arrValues = array (
					$status,
					$oldArticleId,
					$oldArticleId 
			);
			$this->query ( $sql, $arrValues );
			
			$sql='update rel_doc_tag set rstatus = %s where document_id=%s ';
			$arrValues = array (
					$status,
					$oldArticleId
			);
			$this->query ( $sql, $arrValues );
		}
	}
	
	/**
	 * 修改老后台文章的发布状态
	 * @param unknown $articleId
	 * @param unknown $status
	 */
	private function updateOldArticlePublish($articleId, $status) {
		$articleModel = new \haibao\cms\model\data\Article ();
		$tableName = $articleModel->getTableName ();
		$articleIdArr = array();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="' . $tableName . '"';
		if(is_int($articleId)){
			$sql = $sql." and PrimaryKey =%s";
			$articleIdArr = array($articleId);
		}elseif(is_array($articleId)){
			$Ids = join(',',$articleId);
			$sql = $sql . "and PrimaryKey in (".$Ids.")";		
		}
		$result = $this->query ( $sql, $articleIdArr );
		
		$oldArticleId = array();
		$oldArticleIds = "";
		while ( $result->fetch_assoc () ) {
			$oldArticleId[] = $result->getData ( 'OldPrimaryKey' );
		}
		if ($oldArticleId) {
			$this->setConfig ( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$oldArticleIds = join(',',$oldArticleId);
			$sql = "update doc_index set published='".$status."' where document_id in (".$oldArticleIds.") or rootid in (".$oldArticleIds.")";
			$arrValues = array ();
			$this->query ( $sql, $arrValues );
		}
	}
	
	private function updateOldArticleLevel($articleId, $level) {
		$articleModel = new \haibao\cms\model\data\Article ();
		$tableName = $articleModel->getTableName ();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="' . $tableName . '" and PrimaryKey =%s';
		$result = $this->query ( $sql, array (
				$articleId 
		) );
		$oldArticleId = 0;
		while ( $result->fetch_assoc () ) {
			$oldArticleId = $result->getData ( 'OldPrimaryKey' );
		}
		if ($oldArticleId) {
			$this->setConfig ( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			
			$sql = 'update doc_index set priority=%s where document_id=%s or rootid=%s';
			$arrValues = array (
					$level,
					$oldArticleId,
					$oldArticleId 
			);
			$this->query ( $sql, $arrValues );
			
			$sql='update rel_doc_tag set rpriority = %s where document_id=%s ';
			$arrValues = array (
					$level,
					$oldArticleId
			);
			$this->query ( $sql, $arrValues );
		}
	}
	
	/**
	 * 从文章推送到app
	 * @param 文章实体 $articleModel object
	 * @param 表类型 $tableType bool
	 */
	private function addArticleToApp($articleModel,$isInsertOld = false){
		$imageModels = array();
		$imageIds = array();
		$articleId = 0;	
		if($isInsertOld){
			$this->initOldDB();
			$articleId = $articleModel->ArticleOldID;
			$imageModels = $articleModel->ArticleOldImageId;
		}else{
			$this->initNewDB();
			$articleId = $articleModel->Id;
			$imageModels = $articleModel->ArticleImage;
		}
		
		if($articleId && $imageModels){
			foreach($imageModels as $key => $imageModel){
				if(!in_array($imageModel->ImageId, $imageIds) && $imageModel->ImageId){
					$imageIds[] = $imageModel->ImageId;
				}
			}
			
			$datetime = new \DateTime();
			$phoneArticleTagsModel= new \haibao\cms\model\data\PhoneArticleTags();
			$phoneArticleTagsModel->app_tag = $articleModel->AppColum;
			$phoneArticleTagsModel->create_date = $datetime->format('Y-m-d H:i:s');
			$phoneArticleTagsModel->document_id = $articleId;
			$phoneArticleTagsModel->orderdate = $articleModel->PublishTime?$articleModel->PublishTime:$datetime->format('Y-m-d H:i:s');
			$this->addPhoneArtcileTags($phoneArticleTagsModel,$isInsertOld);
			
			$AppColum = array_intersect(array(1,2,3,4,5,6,7),$articleModel->AppColum);
			if($AppColum){
				$appArticleModel = new \haibao\cms\model\data\AppArticle();
				$appArticleModel->document_id=$articleId;
				$appArticleModel->title=$articleModel->Title;
				$appArticleModel->priority=$articleModel->Level;
				if($imageIds){
					$appArticleModel->pic_id = join(',',$imageIds);
					$appArticleModel->fm_pic_id = $imageIds[0];
				}
				$appArticleModel->is_push=1;
				$appArticleModel->pub_status=$articleModel->Published;
				$appArticleModel->visit_nums=0;
				$appArticleModel->create_time= $datetime->format('Y-m-d H:i:s');
				$appArticleModel->pub_time=$articleModel->PublishTime?$articleModel->PublishTime:$datetime->format('Y-m-d H:i:s');
				$appArticleModel->pub_user=$articleModel->Author;
				$this->addAppArticle($appArticleModel,$isInsertOld);
			}
			
			$AppColum = array_intersect(array('98','99'),$articleModel->AppColum);
			
			if($AppColum){
				$phoneSpecialModel=array();
				foreach($AppColum as $key => $value){
					$phoneSpecialModel = new \haibao\cms\model\data\PhoneSpecial();
					if($value=='98'){
						$phoneSpecialModel->spec_type=$phoneSpecialModel::SPEC_TYPE_WEBVIEW;
					}elseif($value=='99'){
						$phoneSpecialModel->spec_type=$phoneSpecialModel::SPEC_TYPE_MASONRY;
					}
					$phoneSpecialModel->spec_title=$articleModel->Title;
					$phoneSpecialModel->spec_desc=$articleModel->Content;
					$phoneSpecialModel->spec_pushed=1;
					$phoneSpecialModel->spec_createtime=$datetime->format('Y-m-d H:i:s');
					$phoneSpecialModel->spec_uptime=$datetime->format('Y-m-d H:i:s');
					$phoneSpecialModel->dateorder=$datetime->format('Y-m-d H:i:s');
					$phoneSpecialModel->visit_nums=0;
					if($imageIds){
						$phoneSpecialModel->pic_id=join(',',$imageIds);
					}
					$phoneSpecialModel->spec_pusedtime=$articleModel->PublishTime?$articleModel->PublishTime:$datetime->format('Y-m-d H:i:s');
					$phoneSpecialModel->spec_article=$articleId;
					$phoneSpecialModel->create_user=$articleModel->Author;
					$phoneSpecialModel->update_user=$articleModel->Author;
					$phoneSpecialModel->pushed_user=$articleModel->Author;
					$phoneSpecialModels[]=$phoneSpecialModel;
				}
				$this->addAppSpecial($phoneSpecialModels,$isInsertOld);
			}
			$this->addAppArticleCategory($articleModel->AppColum,$articleId,$isInsertOld);
			
		}
	}
	
	
	/** 
	 * 推送文章到2.0版本app的phone_article_tags表
	 * @param phone_article_tags的实体 $model object
	 */
	private function addPhoneArtcileTags($model,$isInsertOld){
		if(!$isInsertOld){
			$tableName='PhoneArticleTags';
		}else{
			$tableName='phone_article_tags';
		}
		$sql="delete from ".$tableName." where document_id=".$model->document_id."";
		$this->query($sql);
		$sql="insert into ".$tableName." (`document_id`,`app_tag`,`orderdate`,`create_date`) values ";
		$valArr=array();
		foreach($model->app_tag as $key => $value){
			$sql .= "(%s,%s,%s,%s),";
			array_push($valArr, $model->document_id);
			array_push($valArr, $value);
			array_push($valArr, $model->orderdate);
			array_push($valArr, $model->create_date);
		}
		$sql=rtrim($sql,',');
		$this->query($sql,$valArr);
	}
	
	/**
	 * 推送文章到app_article表
	 * @param app_article的实体 $model object
	 */
	private function addAppArticle($model,$isInsertOld){
		$tableName = "";
		if($isInsertOld){
			$tableName='app_article';
		}else{
			$tableName='AppArticle';
		}
		$sql="select count(*) as count from ".$tableName." where document_id=".$model->document_id." ";
		$result=$this->query($sql);
		while ( $result->fetch_assoc () ) {
			$count = $result->getData ( 'count' );
		}
		
		if ($count == 0) {
			$sql = "INSERT INTO `" . $tableName . "` (
						document_id,
						title,
						priority,
						pic_id,
						fm_pic_id,
						is_push,
						pub_status,
						pub_time,
						pub_user,
						visit_nums,
						create_time,
						create_user
					) 
					values 
					('" . $model->document_id . "',
					 '" . $model->title . "',
					 '" . $model->priority . "',
					 '" . $model->pic_id . "',
					 '" . $model->fm_pic_id . "',
					 '" . $model->is_push . "',
					 '" . $model->pub_status . "',
					 '" . $model->pub_time->format('Y-m-d H:i:s'). "',
					 '" . $model->pub_user . "',
					 '" . $model->visit_nums . "',
					 '" . $model->create_time . "',
					 '" . $model->create_user . "')";
		} else {
			$sql = "update `" . $tableName . "` set 						
						title = '" . $model->title . "',
						priority = '" . $model->priority . "',
						pic_id = '" . $model->pic_id . "',
						fm_pic_id = '" . $model->fm_pic_id . "',
						is_push = '" . $model->is_push . "',
						pub_status = '" . $model->pub_status . "',
						pub_time = '" . $model->pub_time->format('Y-m-d H:i:s') . "',
						pub_user = '" . $model->pub_user . "'											
					where
						document_id = '" . $model->document_id . "'																					
					";
		}		
		$this->query($sql);
	}
	/**
	 * 推送文章到phone_special表
	 * @param phone_special的实体 $model array(object);
	 */
	private function addAppSpecial($model,$isInsertOld){
		$valArr =array();
		if($isInsertOld){
			$tableName='phone_special';
		}else{
			$tableName='PhoneSpecial';
		}
		foreach($model as $key => $value){
			$articleId=$value->spec_article;
		}
		$sql="select count(*) as count from ".$tableName." where spec_article = ".$articleId."  ";
		$result=$this->query($sql);	
		while ( $result->fetch_assoc () ) {
			$count = $result->getData ( 'count' );
		}
		if($count==0){
			$sql="INSERT INTO `" . $tableName . "` (
							spec_type,
							spec_title,
							spec_desc,
							spec_pushed,
							spec_createtime,
							spec_uptime,
							spec_pusedtime,
							spec_article,
							create_user,
							update_user,
							pushed_user,
							pic_id
						) values";
			foreach ($model as $key => $obj){
				$sql .= "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s),";
				array_push($valArr, $obj->spec_type);
				array_push($valArr, $obj->spec_title);
				array_push($valArr, $obj->spec_desc);
				array_push($valArr, $obj->spec_pushed);
				array_push($valArr, $obj->spec_createtime);
				array_push($valArr, $obj->spec_uptime);
				array_push($valArr, $obj->spec_pusedtime);
				array_push($valArr, $obj->spec_article);
				array_push($valArr, $obj->create_user);
				array_push($valArr, $obj->update_user);
				array_push($valArr, $obj->pushed_user);	
				array_push($valArr, $obj->pic_id);	
			}
			$sql=rtrim($sql,',');
			$this->query($sql,$valArr);
		}
				
	}
	
	/**
	 * 推送类型与推送记录关系表
	 * @param 类型 $appColumn array
	 * @param 文章id $articleId
	 */
	private function addAppArticleCategory($appColumn,$articleId,$isInsertOld){
		if(!$isInsertOld){
			$tableName='AppArticleCategory';
		}else{
			$tableName='app_article_category';
		}
		$sql="delete from ".$tableName." where document_id='".$articleId."' ";
		$this->query($sql);	
		$sql="INSERT INTO `".$tableName."` (document_id,column_id) values ";
		$valArr = array();
		foreach($appColumn as $key => $value){
			$sql .= "(%s,%s),";
			array_push($valArr, $articleId);
			array_push($valArr, $value);
		}
		$sql=rtrim($sql,',');
		$this->query($sql,$valArr);
	} 
	
	/**
	 * 
	 */
	private function getAppPublishType(){
		
	}
	
	/**
	 * 修改老文章审核状态
	 */
	private function updateOldArticleAuditType() {
	}
	
	/**
	 * 设置老文章图片的导读图/封面图
	 */
	private function setOldImageType($articleId,$imageInfo,$imgType,$level){
		
		$sql="select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s ";
		$articleResult = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		
		$sql = 'select PrimaryKey,OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s';
		$imageResult = $this->query($sql,array('ImageLibrary',$imageInfo->Id))->fetch_assoc();
		if($articleResult && $imageResult){

			$this->initOldDB();
			$disrel = \haibao\cms\model\data\ArticleProImage::Level_ZERO;
			if($level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
				if($imgType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
					$disrel = \haibao\cms\model\data\ArticleProImage::OLD_SET_PRO_IMG_TYPE;
				}else{
					$disrel = \haibao\cms\model\data\ArticleProImage::OLD_SET_COVER_IMG_TYPE;
				}
			}else if($level == \haibao\cms\model\data\ArticleProImage::Level_ONE){

				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3;
			}else if($level == \haibao\cms\model\data\ArticleProImage::Level_TWO){

				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1;
			}else{
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7;
			}
			$sql = 'delete from `content_photo` where article_id = %s and disrel = %s';
			$this->query ( $sql, array ($articleResult['OldPrimaryKey'],$disrel) );
			
			$valArr = array();
			$sql = "INSERT INTO `content_photo` (`image`,`date`,`article_id`,`title`,`blog_id`,`origin_url`,`pic_id`,`width`,`height`,`disrel`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)";
			array_push ( $valArr, ltrim($imageInfo->Filename, '/') );
			array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
			array_push ( $valArr, $articleResult['OldPrimaryKey'] );
			array_push ( $valArr, $imageInfo->Description );
			array_push ( $valArr, 0 );
			array_push ( $valArr, ltrim($imageInfo->Filename, '/') );
			array_push ( $valArr, $imageResult['OldPrimaryKey'] );
			array_push ( $valArr, $imageInfo->Width );
			array_push ( $valArr, $imageInfo->Height );
			array_push ( $valArr, $disrel );
			$this->query($sql,$valArr);
			
			
			$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = %s ';
			$this->query ( $sql, array ($articleResult['OldPrimaryKey'],$disrel) );
			
			$valArr = array();
			$sql = "INSERT INTO `picsm_pic_obj` (`module_id` ,`obj_id` ,`pic_id`,`disrel`,`adddate`) VALUES (%s,%s,%s,%s,%s)";
			array_push ( $valArr, 1 );
			array_push ( $valArr, $articleResult['OldPrimaryKey'] );
			array_push ( $valArr, $imageResult['OldPrimaryKey']);
			array_push ( $valArr, $disrel );
			array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
			$this->query($sql,$valArr);
		
		}
	}
	
	/**
	 * 同步删除老库的导读图信息
	 */
	private function delOldProImageByProId($articleId,$level){
		
		$sql="select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s ";
		$articleResult = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		$oldArticleId = $articleResult['OldPrimaryKey'];
		if($oldArticleId){
			if($level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_SET_COVER_IMG_TYPE;
			}else if($level == \haibao\cms\model\data\ArticleProImage::Level_ONE){
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3;
			}else if($level == \haibao\cms\model\data\ArticleProImage::Level_TWO){
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1;
			}else{
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7;
			}
			$this->initOldDB();
			$sql = 'delete from `content_photo` where article_id = %s and disrel = %s';
			$this->query ( $sql, array ($oldArticleId,$disrel) );
			$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = %s ';
			$this->query ( $sql, array ($oldArticleId,$disrel) );
		}
	}
	/**
	 * **********************文章老数据通过方法 end*********************************
	 */
}